package com.wnxy.intecepters;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname AuthIntecepter
 * @Description :
 * @Date 2021/3/1 18:06
 * @Created by Yeheng
 */
@Component
public class AuthIntercepter implements HandlerInterceptor {
    private final String AUTH_SERVICE = "http://localhost:8061/auth";

    private final String AUTH_SERV = "http://auth-service/";

    @Autowired
    RestTemplate template;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //0.获取从哪里来
        String backUrl = request.getRequestURL().toString();

        //1.尝试取cookie和token
        String token_r = request.getParameter("token");
        Cookie cookie = WebUtils.getCookie(request,"token");
        String token_c = cookie==null?"": cookie.getValue();
        String token = StringUtils.isEmpty(token_r)?token_c:token_r;
        if (StringUtils.isEmpty(token)){
            response.sendRedirect(AUTH_SERVICE+"?backUrl="+backUrl);
            return false;
        }
        //2.有的话再校验
        boolean flag = Boolean.valueOf(template.getForObject(AUTH_SERV+"verify?token="+token,String.class));
        if (!flag){
            response.sendRedirect(AUTH_SERVICE+"?backUrl="+backUrl);
            return false;
        }
        //3.校验通过放行加设置cookie
        Cookie cookie1 = new Cookie("token", token);
        response.addCookie(cookie1);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
